﻿using System;
using System.Drawing;
using System.Windows.Forms;
using Usido.CRM.Core.ToolHelper;
using Usido.CRM.IRepository;
using Usido.CRM.Models;
using Usido.CRM.Repository;
using log4net;
using Usido.CRM.Core.Extensions;

namespace Usido.CRM.App.Forms
{
    public partial class 药品设置界面 : Form
    {
        private readonly ISysProductRepository ProductReposioty = new SysProductRepository();
        //错误日志
        private readonly ILog logger = LogManager.GetLogger(typeof(药品设置界面));
        //操作日志
        private readonly ISysLogRepository LogReposioty = new SysLogRepository();
        private readonly string UserId = "";
        public 药品设置界面(string userId)
        {
            this.UserId = userId;
            InitializeComponent();
        }
        #region 窗体绘制
        /// <summary>
        /// 解决加载窗体多控件所造成的闪烁 
        /// </summary>
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x02000000;
                return cp;
            }
        }
        #endregion
        private void toolStripDropDownButton1_Click(object sender, EventArgs e)
        {
            TB_SCQY.Text = "";
            TB_XSDW.Text = "";
            TB_YPJM.Text = "";
            TB_YPTYM.Text = "";
            TB_YPGG.Text = "";
            TB_YPBM.Text = "";
            TB_PZWH.Text = "";
            txtYHJ.Text = "100";
            txtLSDW.Text = "0";
            this.tabControl1.SelectedIndex = 1;
        }
        /// <summary>
        /// 新增药品信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            SysProduct m = new SysProduct();
            if (string.IsNullOrEmpty(TB_YPTYM.Text.Trim()) || string.IsNullOrEmpty(TB_YPJM.Text.Trim()) || string.IsNullOrEmpty(TB_XSDW.Text.Trim()) || string.IsNullOrEmpty(TB_SCQY.Text.Trim()))
            {
                MessageBox.Show("请完善信息再保存!");
            }
            else
            {

                m.ManufacturingEnterprise = TB_SCQY.Text.Trim();
                m.MarketingUnit = TB_XSDW.Text.Trim();
                m.ProductCode = TB_YPJM.Text.Trim();
                m.ProductName = TB_YPTYM.Text.Trim();
                m.Specification = TB_YPGG.Text.Trim();
                m.LastUpdateTime = DateTime.Now;
                m.LastUpdateUserId = Convert.ToInt32(UserId);
                m.State = true;
                m.CardNum = txtTM.Text.Trim();
                m.Notation = TB_PZWH.Text.Trim();
                m.RetailPrice = txtLSDW.Text.Trim().ToDecimal();
                m.MemberDiscount = txtYHJ.Text.Trim().ToDecimal();
                if (TB_YPBM.Text.Trim().Length > 0)
                {
                    string Id = dataGridView1.SelectedRows[0].Cells["药品编号"].Value.ToString();
                    SysProduct p = ProductReposioty.Get(Convert.ToInt32(Id));
                    p.LastUpdateTime = DateTime.Now;
                    p.LastUpdateUserId = Convert.ToInt32(UserId);
                    p.ManufacturingEnterprise = m.ManufacturingEnterprise;
                    p.MarketingUnit = m.MarketingUnit;
                    p.Notation = m.Notation;
                    p.ProductCode = m.ProductCode;
                    p.ProductName = m.ProductName;
                    p.CardNum = m.CardNum;
                    p.RetailPrice = m.RetailPrice;
                    p.MemberDiscount = m.MemberDiscount;
                    p.Specification = m.Specification;
                    //编辑
                    if (ProductReposioty.Update(p) > 0)
                    {
                        LogReposioty.AddLog(Convert.ToInt32(UserId), "药品信息修改完成", m);
                        MessageBox.Show("修改成功!");
                        this.tabControl1.SelectedIndex = 0;
                        BindData("");
                    }
                    else
                    {
                        MessageBox.Show("修改失败!");
                    }
                }
                else
                {
                    m.CreateUserId = Convert.ToInt32(UserId);
                    m.CreateTime = DateTime.Now;
                    //新增
                    if (ProductReposioty.Insert(m) > 0)
                    {
                        LogReposioty.AddLog(Convert.ToInt32(UserId), "添加药品完成", m);
                        MessageBox.Show("保存成功!");
                        this.tabControl1.SelectedIndex = 0;
                        BindData("");

                    }
                    else
                    {
                        MessageBox.Show("保存失败!");
                    }
                }
            }
        }

        private void TB_YPTYM_Leave(object sender, EventArgs e)
        {
            if (TB_YPTYM.Text.Trim().Length > 0)
            {
                TB_YPJM.Text = "";
                for (int i = 0; i < TB_YPTYM.Text.Trim().Length; i++)
                {

                    TB_YPJM.Text += Tools.GetPYChar(TB_YPTYM.Text.Trim().Substring(i, 1).Trim());
                }
            }
            else
            {
                TB_YPJM.Text = "";
            }
        }

        /// <summary>
        /// 加载药品列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 药品设置界面_Load(object sender, EventArgs e)
        {
            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            BindData("");
        }

        public void BindData(string where)
        {
            var productList = ProductReposioty.GetProductList(where);
            dataGridView1.AutoGenerateColumns = false;
            dataGridView1.DataSource = productList;
        }
        /// <summary>
        /// 删除药品
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripDropDownButton4_Click(object sender, EventArgs e)
        {
            if (this.tabControl1.SelectedIndex == 0)
            {
                string Id = dataGridView1.SelectedRows[0].Cells["药品编号"].Value.ToString();
                string Tym = dataGridView1.SelectedRows[0].Cells["通用名"].Value.ToString();
                DialogResult RSS = MessageBox.Show(this, $"确定要删除药品{Tym}？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                if (RSS == DialogResult.Yes)
                {
                    int res = ProductReposioty.Delete(int.Parse(Id));
                    if (res > 0)
                    {
                        string LogStr = $"删除{Tym}成功";
                        LogReposioty.AddLog(Convert.ToInt32(UserId), "删除药品成功");
                        BindData("");
                    }
                }
            }
        }
        /// <summary>
        /// 修改药品
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripDropDownButton3_Click(object sender, EventArgs e)
        {
            if (this.tabControl1.SelectedIndex == 0)
            {
                this.tabControl1.SelectedIndex = 1;
                string Id = dataGridView1.SelectedRows[0].Cells["药品编号"].Value.ToString();
                SysProduct m = ProductReposioty.Get(Convert.ToInt32(Id));
                TB_SCQY.Text = m.ManufacturingEnterprise;
                TB_XSDW.Text = m.MarketingUnit;
                TB_YPJM.Text = m.ProductCode;
                TB_YPTYM.Text = m.ProductName;
                TB_YPGG.Text = m.Specification;
                TB_YPBM.Text = m.Id.ToString();
                TB_PZWH.Text = m.Notation;
                txtLSDW.Text = m.RetailPrice.ToString();
                txtYHJ.Text = m.MemberDiscount.ToString();
            }
        }

        private void toolStripDropDownButton2_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        /// <summary>
        /// 检索
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            string seacher = textBox1.Text.Trim();
            BindData($" ProductCode like '%{seacher}%'  or ProductName like '%{seacher}%'  ");
        }

        private void dataGridView1_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                string Id = dataGridView1.SelectedRows[0].Cells["药品编号"].Value.ToString();
                SysProduct m = ProductReposioty.Get(Convert.ToInt32(Id));
                TB_SCQY.Text = m.ManufacturingEnterprise;
                TB_XSDW.Text = m.MarketingUnit;
                TB_YPJM.Text = m.ProductCode;
                TB_YPTYM.Text = m.ProductName;
                TB_YPGG.Text = m.Specification;
                TB_YPBM.Text = m.Id.ToString();
                TB_PZWH.Text = m.Notation;
                txtLSDW.Text = m.RetailPrice.ToString();
                txtYHJ.Text = m.MemberDiscount.ToString();
                this.tabControl1.SelectedIndex = 1;
            }
            catch (Exception ex)
            {
                MessageBox.Show("请选择药品!");
            }
        }

        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,
              e.RowBounds.Location.Y,
              dataGridView1.RowHeadersWidth - 4,
              e.RowBounds.Height);
            TextRenderer.DrawText(e.Graphics,
                  (e.RowIndex + 1).ToString(),
                   dataGridView1.RowHeadersDefaultCellStyle.Font,
                   rectangle,
                   dataGridView1.RowHeadersDefaultCellStyle.ForeColor,
                   TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
            YpCount.Text = "药品总数：" + (dataGridView1.Rows.Count).ToString() + " ";
        }
    }
}
